package com.cc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author 33314
 * @version 1.0
 * @description: TODO
 * @date 2025/6/21 14:13
 */
//配置类
@Configuration
//扫描 controller 包
@ComponentScan("com.cc.controller")
//
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {
    /**
     * @description: TODO 配置消息转换器 处理 HTTP 请求和响应的数据转换。比如将 Java 对象转换为 JSON 字符串
     * @param: converters
     * @return: void
     * @author 33314
     * @date: 2025/6/21 14:25
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(0, converter);
    }

    /**
     * @description: 配置跨域访问
     * @param: registry
     * @return: void
     * @author 33314
     * @date: 2025/6/21 14:28
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://127.0.0.1:5500") // 允许的前端地址
                .allowedMethods("GET", "POST", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true); // 如果需要传递 cookie，设置为 true
    }
}
